import { defineComponent, ref, PropType, createVNode } from 'vue'
import { CloudUploadOutlined } from '@ant-design/icons-vue';
import { bytesToMb, kbToMb, } from '@/utils/tools';
import { isNil } from 'ramda';
import { FileInfo } from '.';
import { Modal, message } from 'ant-design-vue';
import { errorTips, successTips } from '@/utils';
import { OssData, AilOSS } from '@/utils/upload';
import { columns } from './utils';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'

const props = {
    accept: {
        type: String as PropType<string>,
        default: '.jpg,.png,.jpeg',
    },
    /** 文件 */
    fileList: {
        type: Array as PropType<Array<OssData>>,
        required: true
    },
    /** 最大尺寸KB */
    maximumSize: {
        type: Number as PropType<number>,
    },
    beforeUpload: {
        type: Function as PropType<(item: Blob) => boolean | Promise<void>>,
    },
    columns: {
        type: Array as PropType<Array<F.TableColumns>>,
    },
} as const
export default defineComponent({
    name: 'uploadTable',
    props,
    emits: ['change', 'remove'],
    setup(props, { emit, slots }) {
        const OSS = AilOSS
        const fileList = ref<OssData[]>(props.fileList)
        const loading = ref(false)

        async function handleChange(info: FileInfo) {
            loading.value = true
            const curFiles = info.file as File
            try {
                const data = await OSS.uploadOSS(curFiles)
                loading.value = false
                const extension = curFiles.name.split('.').pop()?.toLowerCase();
                if (['jpg', 'jpeg', 'png', 'gif'].includes(extension as string)) {
                    const imageUrl = URL.createObjectURL(curFiles); // 生成临时URL地址
                    const imgElement = new Image();
                    imgElement.src = imageUrl;
                    imgElement.onload = () => {
                        // 如果想进行更多操作或者显示到页面上，可以根据需求修改下面的代码
                        const file = {
                            ...data,
                            name: curFiles.name,
                            type: curFiles.type,
                            byte: bytesToMb(curFiles.size),
                            size: `${imgElement.width}x${imgElement.height}`,
                            width: imgElement.width,
                            height: imgElement.height,
                        }

                        fileList.value.push(file)
                        console.log(file, curFiles);

                        emit('change', file as OssData)
                    };
                    return
                }
                const file = {
                    ...data,
                    type: curFiles.type,
                    byte: bytesToMb(curFiles.size),
                    name: curFiles.name
                }
                emit('change', file as OssData)
            } catch (error) {
                loading.value = false
                errorTips('上传文件失败:' + error)
            }

        }
        function beforeUpload(file: Blob) {
            const reg = props.accept.split(',').map(ext => ext.trim().replace(/\.[^.]+$/, match => match.replace('.', ''))).join('|')
            if (!new RegExp(`\\.(${reg})$`, 'i').test((file as any).name.toLowerCase())) {
                message.error(`上传格式不正确，请上传${props.accept}格式`)
                return Promise.reject()
            }
            if (props.maximumSize && (file.size / 1024) > props.maximumSize) {
                message.error(`上传文件不能超过${kbToMb(props.maximumSize)}M`);
                return Promise.reject()
            }
            /** 自定义前置事件 */
            if (props.beforeUpload) {
                return props.beforeUpload(file)
            }
            return false
        }
        async function onRemove(index: number) {
            const file = fileList.value[index]
            if (isNil(file.url)) {
                message.warning('删除失败，文件地址为空')
                return
            }
            try {
                Modal.confirm({
                    title: '是否确定删除该数据？',
                    icon: createVNode(ExclamationCircleOutlined),
                    onOk: async () => {
                        /** 待优化 */
                        // const { success } = await OSS.removeOSS(file.filename as string)
                        // if (success) {
                        //     successTips('删除成功')
                        // }
                        fileList.value.splice(index, 1)
                        emit('remove', file as OssData)
                    },
                })

            } catch (error: any) {
                message.error(error)
            }
        }
        function actionRender({ index }: F.RableSlotScope<any>) {
            return (
                <a-space size="middle">
                    <a-button type="link" block danger onClick={() => onRemove(index)}>
                        删除
                    </a-button>
                </a-space>
            )
        }
        return () => <div>
            <a-upload-dragger
                before-upload={beforeUpload} name="file"
                multiple
                showUploadList={false}
                accept={props.accept}
                onChange={handleChange}>
                <p class="ant-upload-drag-icon flexBox">
                    <CloudUploadOutlined style="margin-right: 20px" />将目录或多个文件拖拽到此进行扫描
                </p>
                <p class="ant-upload-text">支持文件类型：{props.accept.split(',').join('、')}</p>
                {!isNil(props.maximumSize) && (
                    <p class="ant-upload-hint">
                        每个文件允许最大尺寸：{kbToMb(props.maximumSize)}M
                    </p>
                )}

            </a-upload-dragger>
            <div style="margin: 10px 0">
                <a-space size="middle">
                    <a-upload
                        name="avatar"
                        show-upload-list={false}
                        before-upload={beforeUpload}
                        onChange={handleChange}
                        accept={props.accept}
                        multiple

                    >
                        <a-button type="primary" >
                            选择文件
                        </a-button>
                    </a-upload>

                    <a-upload
                        name="avatar"
                        show-upload-list={false}
                        before-upload={beforeUpload}
                        onChange={handleChange}
                        accept={props.accept}
                        directory
                    >
                        <a-button type="primary" >
                            选择文件夹
                        </a-button>
                    </a-upload>
                </a-space>
            </div>
            <a-table
                rowKey="filename"
                tableKey="uploadTableTable"
                dataSource={props.fileList}
                columns={props.columns ?? columns} pagination={true}
                v-slots={{ actionRender, ...slots }}
            >

            </a-table>
        </div >
    }
})